import { contextBridge, ipcRenderer } from 'electron'
import ipcEventChannels from '../common/ipcEventChannels'

contextBridge.exposeInMainWorld('$theme', {
    change(value) {
        ipcRenderer.send(ipcEventChannels.THEME_CHANGE, value)
    },
    get: () => ipcRenderer.invoke(ipcEventChannels.THEME_GET),
    isDark: () => ipcRenderer.invoke(ipcEventChannels.THEME_IS_DARK)
})

contextBridge.exposeInMainWorld('$window', {
    invoke(command) {
        ipcRenderer.send(ipcEventChannels.WIN_INVOKE, command)
    },
    listen(event, listener) {
        switch (event) {
            case 'maximize':
                ipcRenderer.send(ipcEventChannels.WIN_LISTEN_MAXIMIZE)
                ipcRenderer.on(ipcEventChannels.WIN_LISTEN_MAXIMIZE_CALLBACK, listener)
                break
            case 'unmaximize':
                ipcRenderer.send(ipcEventChannels.WIN_LISTEN_UNMAXIMIZE)
                ipcRenderer.on(ipcEventChannels.WIN_LISTEN_UNMAXIMIZE_CALLBACK, listener)
                break
            case 'minimize':
                ipcRenderer.send(ipcEventChannels.WIN_LISTEN_MINIMIZE)
                ipcRenderer.on(ipcEventChannels.WIN_LISTEN_MINIMIZE_CALLBACK, listener)
                break
        }
    },
    isMaximized: () => ipcRenderer.invoke(ipcEventChannels.WIN_IS_MAXIMIZED)
})

contextBridge.exposeInMainWorld('$menu', {
    open(type, listener) {
        let showChannel, callbackChannel
        switch (type) {
            case 'chatlist':
                showChannel = ipcEventChannels.MENU_CHATLIST_SHOW
                callbackChannel = ipcEventChannels.MENU_CHATLIST_CALLBACK
                break
            case 'mainmenu':
                showChannel = ipcEventChannels.MENU_MAINMENU_SHOW
                callbackChannel = ipcEventChannels.MENU_MAINMENU_CALLBACK
                break
        }
        ipcRenderer.send(showChannel)
        ipcRenderer.once(callbackChannel, (_, message) => {
            listener(message)
        })
    }
})

contextBridge.exposeInMainWorld('$store', {
    getChatlist: () => ipcRenderer.invoke(ipcEventChannels.STORE_GET_CHATLIST),
    setChatlist(value) {
        ipcRenderer.send(ipcEventChannels.STORE_SET_CHATLIST, value)
    },
    getAllSettings: () => ipcRenderer.invoke(ipcEventChannels.STORE_GET_ALL_SETTINGS),
    getSetting: (key) => ipcRenderer.invoke(ipcEventChannels.STORE_GET_SETTINGS, key),
    setSetting(key, value) {
        ipcEventChannels.send(ipcEventChannels.STORE_SET_SETTINGS, key, value)
    }
})
